Not in this example. But sometimes it does, when values are close to the limit of what can be represented in 16 bits.
Here is another example:
short x = 12; short y = 3; short value; value = x / y;
The expression x / y
divides a
32-bit value 12 by a 32-bit value 3, even though the variables x
and y
are only 16 bits wide.
The calculation produces a 32-bit result.
Because the 32-bit result does not fit in the 16 bits of value
the compiler will not compile the last statement.
This can be completely baffling when it happens to you.
C:\Private>javac ShortStuff.java ShortStuff.java:9: possible loss of precision found : int required: short result = x / y; ^ 1 error C:\Private>
For professional programmers, details like these are sometimes important.
But for most programs, just use int
or
long
for integers and double
for floating point.
This will keep you out of trouble (usually).
If you can't avoid the problem, use a type cast, as described in chapter 28.
Do you expect that a modern electronic calculator will give you the same
answer as Java for the expression
(31.5 - 12)/4.1
?